﻿singleApp.controller('goodsCtrl', ['$http', '$scope', 'AppDataService', '$timeout', function ($http, $scope, AppDataService, $timeout) {
    $scope.model_tabs = [];
    $scope.model_index = 100;
    $scope.model_statuslist = AppDataService.StatusList;
    $scope.model_categories = [];
    $scope.model_goods = [];
    $scope.base_img_url = "";

    //Init
    $scope.init = function () {
        $scope.base_img_url = window.singleConfig.rootUrl + "/public/goods_imgs/";

        layer.load(2);
        var api_url = window.singleConfig.rootUrl + "api/admin/GoodsService/getAll";
        $http.get(api_url).then(function (result) {
            $scope.model_goods = result.data.data;
            $scope.model_categories = result.data.categories;
            layer.closeAll();
        }, function () { });
    };

    $scope.init();

    /*
     * add new tab
     */
    $scope.addNew = function (item) {
        var tab = {};
        

        if (item == null) {
            tab = {
                id: "div" + $scope.model_index++,
                title: "添加新商品",
                type: "add",
                data: {
                    id: 0,
                    img: "",
                    name: "",
                    description: "",
                    cat_id: $scope.model_categories[0].id,
                    status: "1",
                    integral: 0,
                    original_integral: 0,
                    stock_num: 0,
                    view_count: 0,
                }
            };
        }
        else {
            tab = {
                id: "div" + $scope.model_index++,
                title: "编辑商品 - " + item.name,
                type: "update",
                data: {
                    id: item.id,
                    img: item.img,
                    name: item.name,
                    description: item.description,
                    cat_id: item.cat_id,
                    status: item.status,
                    integral: item.integral,
                    original_integral: item.original_integral,
                    stock_num: item.stock_num,
                    view_count: item.view_count,
                }
            };
        }

        $scope.model_tabs.push(tab);
        setTimeout(function () {
            $('#myTab a:last').tab('show');
            var editor = new Simditor({
                textarea: $('#divDescription' + tab.id),
                upload: {
                    url: window.singleConfig.rootUrl + "api/common/FileService/uploadGoodsDescriptionImage",
                    params: {},
                    fileKey: 'img_content',
                    connectionCount: 3,
                    leaveConfirm: 'Uploading is in progress, are you sure to leave this page?'
                }
            });
            if (item != null) {
                editor.setValue(item.description);
            }
            angular.element(document.querySelector('#imgThumb' + tab.id)).on('change', $scope.crop);
        }, 100);
    };

    /*
     * delete tab
     */
    $scope.deleteTab = function (tab) {
        angular.forEach($scope.model_tabs, function (data, index, array) {
            if (tab.id == data.id) {
                $scope.model_tabs.splice(index, 1);
                setTimeout(function () {
                    $('#myTab a:last').tab('show');
                }, 100);
            }
        });
    };

    $scope.confirmAddNew = function (tab) {
        if (tab.data.name == "") {
            layer.msg("商品名称不能为空！");
            return;
        }

        tab.data.description = $('#divDescription' + tab.id).val();
        angular.forEach($scope.model_categories, function (data, index, array) {
            if (data.id == tab.data.cat_id) {
                tab.data.cat_name = data.name;
            }
        });

        api_url = window.singleConfig.rootUrl + 'api/admin/GoodsService/' + tab.type;
        layer.load(2);
        $http({
            method: 'POST',
            url: api_url,
            data: $.param(tab.data),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        .then(function (result) {
            var data = result.data;
            if (data.code == "success") {
                layer.closeAll();
                layer.msg("提交成功!");
               
                $timeout(function () {
                    $scope.deleteTab(tab);
                    $scope.init();
                }, 1000);
            }
            else {
                layer.closeAll();
                layer.msg(data.message);
            }
        },function (data) {
            layer.closeAll();
            layer.msg("Add failed!");
        });
    };

    $scope.model_cropimg = { item: {}, myImage: "", myCroppedImage: "", bounds: { left: 0, right: 0, top: 0, bottom: 0 } };
    $scope.crop = function (evt) {
        var tabid = evt.currentTarget.id.replace("imgThumb", "");
        var tab = {};
        angular.forEach($scope.model_tabs, function (data,index,array) {
            if (data.id == tabid) {
                tab = data;
            }
        });

        var file = evt.currentTarget.files[0];
        var reader = new FileReader();
        reader.onload = function (evt) {
            $scope.$apply(function ($scope) {
                $scope.model_cropimg = {
                    item: tab,
                    myImage: evt.target.result,
                    myCroppedImage: "",
                    bounds: { left: 0, right: 0, top: 0, bottom: 0 },
                };
            });
            layer.open({
                type: 1,
                title: '裁剪图片',
                content: $('#divCropImg'),
                area: ['1200px', '650px'],
                cancel: function (index) {
                    layer.closeAll();
                }
            });
        };
        reader.readAsDataURL(file);
    };

    $scope.confirmCropImg = function () {        
        layer.load(2);
        var api_url = window.singleConfig.rootUrl + "api/common/FileService/uploadCropedPostFile";
        $http({
            method: 'POST',
            url: api_url,
            data: $.param({
                img_content: $scope.model_cropimg.myCroppedImage,
                title: $scope.model_cropimg.item.data.title,
            }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
		.then(function (result) {
		    var data = result.data;
		    if (data.code == "success") {
		        $scope.model_cropimg.item.data.img = data.FileName;
		        layer.closeAll();
		    }
		},function (data) {
		    layer.closeAll();
		    layer.msg("Error to save croped image.");
		});
    };

    /*
     * delete
     */
    $scope.delete = function (item) {
        layer.confirm('确定删除这个商品吗 ?', { icon: 3, title: '消息', btn: ['确定', '取消'] }, function (index) {
            layer.load(2);
            var api_url = window.singleConfig.rootUrl + "api/admin/GoodsService/delete?id=" + item.id;
            $http.get(api_url).then(function (result) {
                angular.forEach($scope.model_goods, function (data, index, array) {
                    if (item.id == data.id) {
                        $scope.model_goods.splice(index, 1);
                    }
                });
                layer.closeAll();
            }, function () { });
        });
    };

    /*
     * User Context Menu
     */
    $scope.menuOptionsUser = [
            ['Edit', function ($itemScope) {
                $scope.addNew($itemScope.item);
            }],
            null,
            ['Toggle Status', function ($itemScope) {
                layer.msg("Comming soon !");
            }]
    ];
}]);